package com.lry.web.user.controller;

import com.lry.web.rests.GeneratorValidateCode;
import com.lry.web.user.entity.User;
import com.lry.web.user.service.UserService;
import com.lry.web.util.Result;
import com.lry.web.util.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    HttpServletRequest request;

    /**
     * 生成验证码图片
     *
     */
    @RequestMapping(value = "/getValidateCode")
    @ResponseBody
    public String getValidateCode(HttpServletResponse response) {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        GeneratorValidateCode instance = new GeneratorValidateCode();

        //储存验证码到session中，key为ValidateCode
        request.getSession().setAttribute("ValidateCode", instance.getCode());
        try {
            instance.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }
    @RequestMapping("/login/{username}/{password}/{ValidateCode}")
    @ResponseBody
    public Result login(@PathVariable(value = "username") String username,@PathVariable(value = "password") String password,@PathVariable(value = "ValidateCode") String validateCode){
        String validateCodes = (String) request.getSession().getAttribute("ValidateCode");
        if(validateCode.equals(validateCodes.toLowerCase())){
        //创建用户名密码的身份验证的token
        UsernamePasswordToken token = new  UsernamePasswordToken(username,password);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
            return ResultUtil.success();
        } catch (AuthenticationException e) {
            return ResultUtil.error(1,"账号或密码错误");
        }
        }
        return ResultUtil.error(1,"验证码错误");

    }

    @RequestMapping("/updatePassword/{password}")
    @ResponseBody
    public Result updatePassword(@PathVariable(value = "password") String password){
        User user = (User) request.getSession().getAttribute("user");
        int i = userService.updatePassword(user,password);
        if(i==0){
            return ResultUtil.error(1,"修改失败");
        }else{
            return ResultUtil.success();
        }


    }

    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        /**
         * 用户登出，销毁认证
         */
        subject.logout();
        return "login";
    }




}
